﻿package _A_TJTable;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
/**
 * 2011-6-3 23:34:54
 * @author Administrator
 * 通过CellRender来设置单元格的填充颜色
 */
public class JTable_CellRender {
    JFrame frame;
    Container contentPane;
    JScrollPane jsp;
    JTable table;
    public JTable_CellRender(){
        frame=new JFrame("表格组件测试");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane=frame.getContentPane();
        contentPane.setLayout(new BorderLayout());
        String name[]={"姓名","语文","数学"};
        Object data[][]={
            {"王鹏",91,100},
            {"李兵",99,89},
            {"肖龙",100,100}
        };
        DefaultTableModel dtm=new DefaultTableModel(data,name);
        dtm.setColumnCount(10);
        dtm.setRowCount(10);
        table=new JTable(dtm);
        //设置表格属性
        table.setRowHeight(30);
        table.setCellSelectionEnabled(true);
        table.setPreferredScrollableViewportSize(new Dimension(400,100));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        //设置列属性
        TableColumnModel tcm=table.getColumnModel();
        tcm.setColumnMargin(10);
        DefaultTableCellRenderer dtcr=new DefaultTableCellRenderer(){
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                if(row%2==0){
                    this.setBackground(Color.white);
                }
                else{
                    this.setBackground(Color.green);
                }
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        };
        for(int i=0;i<tcm.getColumnCount();i++){
            TableColumn tc=tcm.getColumn(i);
            tc.setPreferredWidth(100);
            tc.setCellRenderer(dtcr);
//            tc.setMinWidth(50);
        }
        jsp=new JScrollPane(table);
        contentPane.add(jsp,BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public static void main(String args[]){
        new JTable_CellRender();
    }
}
